<?php

namespace App\Models;

use App\Api\Filters\BooksFilters;
use App\Api\Helpers\Services\BookService;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Book extends Model
{

    use SoftDeletes;

    protected $guarded = [];

    public function comments(){

        return $this->hasMany(Post::class,'book_num','book_num');

    }

    public function creater(){
        return $this->belongsTo(User::class,'uid','id');
    }


    public function chapters(){

        return $this->hasMany(Chapter::class,'book_num','book_num');

    }


    // 通过加入书架量  bookshelf 确定收藏数

    public function collections(){

        return $this->hasMany(Bookshelf::class,'book_num','book_num');

    }


    public function readRecords(){

        return $this->hasMany(ReadRecord::class,'book_id','id');

    }


    // 书籍的打赏记录
    public function rewarded(){
        return $this->hasMany(GivedGift::class,'relation','book_num')->where('type',2);
    }



    // 对书籍进行过滤
    public function scopeFilter($query, BooksFilters $filters)
    {

        return $filters->apply($query);
    }

    public function scopeClearOrders($query){
        $query->getQuery()->orders = [];
        return $query;
    }


    public function bookType(){

        return $this->belongsTo(BookType::class,'type','id');

    }


    public function syncBookWords(){

        $this->update([
            'words' => (new  BookService($this))->getWordsCount()
        ]);

        return $this;

    }


    public function recommendBook(){

        return $this->hasMany(BookRecommend::class);
    }


    

    public function scopeNormal($query){

        return $query->where([
            'isopen' => 1,
            'isrelease' => 1
        ]);

    }


    public function giftList(){




    }

    protected static function boot()
    {
        parent::boot();


        static::creating(function ($book){

            $book->book_num = md5(time());
            $book->create_time = time();
            $book->last_modify_time = time();

        });

        static::updating(function ($book){

            $cover = $book->cover;

            $book->cover = $cover;


            if(! preg_match('/http:\/\/[\w.]+[\w\/]*[\w.]*\??[\w=&\+\%]*/is',$cover)){


                if (substr($cover,0,4) == 'head'){
                    $cover = substr($cover,5);

                }

                $book->cover = url('api/user/output/'.$cover);

            }


        });

    }


    public function recommends(){

        return $this->morphMany(Recommend::class, 'recommendable');

    }


}
